﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Sunny.Entity;
using Sunny.Model.RedisCache;
using Sunny.Model.RequestParam;
using Sunny.Service;
using Sunny.Util.Attributes;
using Sunny.Util.Enums;

namespace Sunny.Api.Controllers
{
    [ApiController]
    [Route("/system/config")]
    public class SysConfigController
    {
        private readonly ConfigService _configService;

        public SysConfigController(ConfigService configService)
        {
            _configService = configService;
        }
        
        #region 根据参数键名查询参数值

        [HttpGet("configKey/{configKey}")]
        public async Task<Result> ConfigKey([FromRoute]string configKey)
        {
            Console.WriteLine("configKey:"+configKey);
            var configValue = await _configService.GetConfigByKey(configKey);
            Console.WriteLine(configValue);
            return  Result.Success(configValue);
        }
        #endregion

        #region 参数配置列表
        [HasPermission("system:config:list")]
        [HttpGet("list")]
        public async Task<Result> List([FromQuery]ConfigListParam param)
        {
            (List<SysConfig> sysConfigs,int total) = await _configService.List(param);
            return Result.Success(new
            {
                rows = sysConfigs,total
            });
        }

        #endregion

        #region 参数配置添加
        [HasPermission("system:config:add")]
        [LogInfo(Title = "参数配置管理",BusinessType = BusinessType.Insert)]
        [HttpPost]
        public async Task<Result> Add([FromBody]SysConfig sysConfig)
        {
            await _configService.Add(sysConfig);
            return Result.Success();
        }

        #endregion

        #region 获取配置详细信息
        [HasPermission("system:config:query")]
        [HttpGet("{configId}")]
        public async Task<Result> Info([FromRoute]int configId)
        {
            SysConfig sysConfig = await _configService.GetConfigById(configId);
            return Result.Success(sysConfig);
        }
        #endregion
        
        #region 参数配置修改
        [HasPermission("system:config:edit")]
        [LogInfo(Title = "参数配置管理",BusinessType = BusinessType.Update)]
        [HttpPut]
        public async Task<Result> Update([FromBody]SysConfig sysConfig)
        {
            await _configService.Update(sysConfig);
            return Result.Success();
        }

        #endregion
        
        #region 参数配置删除
        [HasPermission("system:config:remove")]
        [LogInfo(Title = "参数配置管理",BusinessType = BusinessType.Delete)]
        [HttpDelete("{configId}")]
        public async Task<Result> Delete([FromRoute]int configId)
        {
            await _configService.Delete(configId);
            return Result.Success();
        }

        #endregion
    }
}